package com.mac.hosp_pre.interceptor;

import com.mac.hosp_pre.base.UserBaseDto;
import com.mac.hosp_pre.except.ResultCodeEnum;
import com.mac.hosp_pre.handler.RefreshTokenHandler;
import com.mac.hosp_pre.reply.R;
import com.mac.hosp_pre.util.JwtUtil;
import com.mac.hosp_pre.util.servlet.ServletUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



public interface PortalInterceptor extends HandlerInterceptor {

    @Override
    default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = JwtUtil.getToken(request);
        if (StringUtils.isBlank(token)){
            ServletUtils.writeJSON(response, R.error(ResultCodeEnum.UNAUTHORIZED));
            return false;
        }
        Long userId = JwtUtil.getUserId(request);
        if (userId == null){
            ServletUtils.writeJSON(response, R.error(ResultCodeEnum.UNAUTHORIZED));
            return false;
        }
        UserBaseDto userInfo = getUserInfo(token,userId);
        RefreshTokenHandler consumer= getRefreshTokenHandler();
        JwtUtil.verifyToken(token,false,userInfo, consumer);
        return true;
    }

    UserBaseDto getUserInfo(String token,Long userId);
    RefreshTokenHandler getRefreshTokenHandler();
}
